package com.lyb.fileserver.filters;

import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by 李一博 on 13:54 2019/6/26.
 */

public class UrlFilter implements Filter {

    @Value("${server.adminpassword}")
    private String adminpassword;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化管理员密码："+adminpassword);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();
        System.out.println("--------------------->过滤请求地址" + requestURI);
        String adminpass = (String) req.getSession().getAttribute("adminpass");
        if (adminpass == null || (!(adminpassword.equals(adminpass)))) {
            response.sendRedirect("/page/login");
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("...................");
    }
}
